package com.alpha.servlets;

import java.io.IOException;
import java.sql.SQLException;

import javax.naming.NamingException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.HttpConstraint;
import javax.servlet.annotation.ServletSecurity;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.alpha.bom.Student;
import com.alpha.bom.User;
import com.alpha.dao.CategoryDao;
import com.alpha.dao.ProfessorDao;
import com.alpha.dao.StudentDao;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
@ServletSecurity(@HttpConstraint(rolesAllowed = {"admin","user"}))
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private static Logger logger = Logger.getLogger(LoginServlet.class.getName());
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		logger.info(this.getClass().getSimpleName()+" post method started.");
		
		User user = null;
		
		CategoryDao cDao = new CategoryDao();
		ServletContext application = this.getServletContext();
		if(application.getAttribute("categories")==null){
			try {
				application.setAttribute("categories", cDao.retrieveAllCategories());
			} catch (NamingException e) {
				logger.error(e.getMessage());
				return;
			} catch (SQLException e) {
				logger.error(e.getMessage());
				return;
			}
		}
		
		//instantiation of ProfessorDao and StudentDao
		ProfessorDao pDao = new ProfessorDao();
		StudentDao sDao = new StudentDao();
		
		try {
			if(request.isUserInRole("admin")){
				user = pDao.retrieveProfessor(Integer.parseInt(request.getRemoteUser().toString()));
			} else if(request.isUserInRole("user")){
				user = sDao.retrieveStudent(Integer.parseInt(request.getRemoteUser().toString()));
				if((user instanceof Student) && !((Student)user).isActivated()){
					user = null;
				}
			} else {
				response.sendRedirect("Login.jsp?message=Invalid+login.");
				return;
			}
		} catch (NamingException e) {
			logger.error(e.getMessage());
			return;
		} catch (SQLException e) {
			logger.error(e.getMessage());
			return;
		}
		
		if(user!=null){
				HttpSession session = request.getSession();
				session.setAttribute("user", user);
				response.sendRedirect("HomeServlet");
		}else{
        	response.sendRedirect("Login.jsp?message=Invalid+username+and+password.");
		}
	}

}
